/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcBuyActivity.java
 *   @Date: 19-1-18 下午4:43
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.ui;

import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cc.shinichi.library.ImagePreview;
import cc.shinichi.library.bean.ImageInfo;
import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.otc.presenter.OtcBuyPresenter;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DateUtils;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.utils.TextColorUtils;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.images.CImageLoader;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcOrderInfoResponse;

public class OtcBuyActivity extends BaseActivity<OtcBuyPresenter, OtcBuyPresenter.OtcBuyUI> implements OtcBuyPresenter.OtcBuyUI, View.OnClickListener {
    private String[] payWayArray;
    private AlertView payWayAlertView;
    private HashMap<String, OtcOrderInfoResponse.PaymentTermListBean> payWayMap = new HashMap<String, OtcOrderInfoResponse.PaymentTermListBean>();
    private Button orderStatusBtn;
    private CountDownTimer countDownTimer;
    private Button cancelBtn;
    private Button appealBtn;
    private boolean isAppealCountDown = false;
    private boolean isPayCountDown = false;
    private CountDownTimer appealCountDownTimer;
    private boolean isBuy = true;
    private OtcOrderInfoResponse.PaymentTermListBean currentPaymentBean;
    private OtcOrderInfoResponse currentOrderInfo;
    private TopBar topBar;
    private TextView orderPayWay;
    private boolean isNewStatus = true;
    private TextView otcBuyQuantityTx;
    private boolean mShowRiskTips;
    private RadioGroup payWayRadioGroup;

    @Override
    protected int getContentView() {
        return R.layout.activity_otc_buy_layout;
    }

    @Override
    protected OtcBuyPresenter createPresenter() {
        return new OtcBuyPresenter();
    }

    @Override
    protected OtcBuyPresenter.OtcBuyUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightImg(R.mipmap.icon_message);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (currentOrderInfo != null) {
//                    topBar.setRightRedPointVisiblity(View.GONE);
                    switchRedPointIcon(false);
                    IntentUtils.goOtcMessage(OtcBuyActivity.this, currentOrderInfo);
                }
            }
        });
        orderStatusBtn = viewFinder.find(R.id.order_status_btn);
        cancelBtn = viewFinder.find(R.id.btn_cancel);
        appealBtn = viewFinder.find(R.id.btn_appeal);
        orderPayWay = viewFinder.textView(R.id.order_pay_way);
        otcBuyQuantityTx = viewFinder.textView(R.id.title_otc_buy_quantity);
        payWayRadioGroup = viewFinder.find(R.id.payWayRadioGroup);
    }

    private void switchRedPointIcon(boolean isVisibleRedPoint) {
        topBar.setRightImg(isVisibleRedPoint ? R.mipmap.messageicon_message_red : R.mipmap.icon_message);
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.title).setOnClickListener(this);
        viewFinder.find(R.id.order_pay_way).setOnClickListener(this);
        viewFinder.find(R.id.qrcode).setOnClickListener(this);
        viewFinder.find(R.id.order_id).setOnClickListener(this);
        viewFinder.find(R.id.bank_no_copy).setOnClickListener(this);
        viewFinder.find(R.id.bank_name_copy).setOnClickListener(this);
        viewFinder.find(R.id.bank_branch_copy).setOnClickListener(this);
        viewFinder.find(R.id.trade_username_copy).setOnClickListener(this);
        viewFinder.find(R.id.pay_account_copy).setOnClickListener(this);
        viewFinder.find(R.id.pay_username_copy).setOnClickListener(this);
        viewFinder.find(R.id.order_status_btn).setOnClickListener(this);
        viewFinder.find(R.id.btn_cancel).setOnClickListener(this);
        viewFinder.find(R.id.btn_appeal).setOnClickListener(this);
        viewFinder.textView(R.id.order_id).setOnClickListener(this);
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    public void showIsShowRiskTips(boolean isShowRiskTips) {
        mShowRiskTips = isShowRiskTips;
        if (currentOrderInfo != null) {
            String tokenId = currentOrderInfo.getTokenId();
            if (!TextUtils.isEmpty(tokenId)) {
                viewFinder.find(R.id.tip_risk).setVisibility(isShowRiskTips && KlineUtils.isRiskTokenId(tokenId) ? View.VISIBLE : View.GONE);
            }
        }
    }

    @Override
    public void showOrderInfo(boolean isAutoReq, OtcOrderInfoResponse orderInfo) {
        if (orderInfo != null) {
            showIsShowRiskTips(mShowRiskTips);
            if (currentOrderInfo != null) {
                isNewStatus = currentOrderInfo.getStatus() != orderInfo.getStatus();
            }
            currentOrderInfo = orderInfo;
            int side = orderInfo.getSide();
            isBuy = (side == 0);
            viewFinder.textView(R.id.title).setText(getString(side == 0 ? R.string.string_otc_payment : R.string.string_otc_receivables) + " " + orderInfo.getAmount() + " " + orderInfo.getCurrencyId());
            otcBuyQuantityTx.setText(orderInfo.getQuantity() + " " + orderInfo.getTokenName());
            viewFinder.textView(R.id.user_name).setText(orderInfo.getTargetNickName());
            viewFinder.textView(R.id.turnoverRate).setText("（" + orderInfo.getRecentOrderNum() + "/" + orderInfo.getRecentExecuteRate() + "%）");
            viewFinder.textView(R.id.price).setText(orderInfo.getPrice() + " " + orderInfo.getCurrencyId());
            viewFinder.textView(R.id.order_id).setText(orderInfo.getId());
            viewFinder.textView(R.id.order_create_time).setText(DateUtils.getSimpleTimeFormat(orderInfo.getCreateDate()));

            boolean isHasComfirmPayment = false;
            OtcOrderInfoResponse.PaymentTermListBean paymentTermResult = orderInfo.getPaymentTermResult();
            if (paymentTermResult != null) {
                String accountNo = paymentTermResult.getAccountNo();
                if (!TextUtils.isEmpty(accountNo)) {
                    isHasComfirmPayment = true;
                }
            }
            List<OtcOrderInfoResponse.PaymentTermListBean> paymentTermList;
            if (isHasComfirmPayment) {
                paymentTermList = new ArrayList<>();
                paymentTermList.add(paymentTermResult);
            } else {
                paymentTermList = orderInfo.getPaymentTermList();
            }
            if (!payWayMap.isEmpty()&&payWayMap.size()>0) {
                return;
            }
            if (paymentTermList != null) {
                payWayArray = new String[paymentTermList.size()];
                if (isNewStatus) {
                    payWayRadioGroup.removeAllViews();

                    for (OtcOrderInfoResponse.PaymentTermListBean paymentTermBean : paymentTermList) {
                        int paymentType = paymentTermBean.getPaymentType();

                        if (paymentType == 0) {
                            paymentTermBean.setPayName(getString(R.string.string_pay_union) + ":" + paymentTermBean.getAccountNo());
                        } else if (paymentType == 1) {
                            paymentTermBean.setPayName(getString(R.string.string_pay_alipay) + ":" + paymentTermBean.getAccountNo());
                        } else if (paymentType == 2) {
                            paymentTermBean.setPayName(getString(R.string.string_pay_wechat) + ":" + paymentTermBean.getAccountNo());
                        }
                        int index = paymentTermList.indexOf(paymentTermBean);
                        payWayArray[index] = paymentTermBean.getPayName();
                        payWayMap.put(paymentTermBean.getPayName(), paymentTermBean);

                        //只有一种支付方式或者是默认的支付方式
                        if (index == 0 || paymentType == orderInfo.getPaymentType()) {
                            updateShowPayWay(paymentTermBean);
                        }

                        boolean blackMode = CommonUtil.isBlackMode();
                        RadioButton radioButton = new RadioButton(this);
                        radioButton.setTag(paymentTermBean.getPayName());
                        radioButton.setText(paymentTermBean.getPayName());
                        radioButton.setChecked(currentPaymentBean.getPayName().equals(paymentTermBean.getPayName()));
                        radioButton.setButtonDrawable(blackMode ? R.drawable.checkbox_style_night : R.drawable.checkbox_style);
                        radioButton.setTextColor(SkinColorUtil.getDark(this));
                        radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                        radioButton.setId(View.generateViewId());
                        radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (isChecked) {
                                    String payName = (String) buttonView.getTag();
                                    OtcOrderInfoResponse.PaymentTermListBean paymentTermListBean = payWayMap.get(payName);
                                    if (paymentTermListBean != null) {
                                        updateShowPayWay(paymentTermListBean);
                                    }
                                }
                            }
                        });
                        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);

                        layoutParams.topMargin = PixelUtils.dp2px(8);
                        layoutParams.bottomMargin = PixelUtils.dp2px(8);
                        radioButton.setLayoutParams(layoutParams);
                        payWayRadioGroup.addView(radioButton);

                    }
                }
            }

            if (isBuy) {
                viewFinder.textView(R.id.tip_normal).setText(getString(R.string.string_format_otc_buy_tips, getString(R.string.app_name), getString(R.string.app_name)));
            } else {
                viewFinder.textView(R.id.tip_normal).setText(getString(R.string.string_format_otc_sell_tips));
            }

            updateOrderStatus(orderInfo);
            currentOrderInfo = orderInfo;
        }

    }

    @Override
    public void showCancelOrderSuccess() {
        ToastUtils.showShort(getString(R.string.string_order_canceled));
        if (currentOrderInfo != null) {
            currentOrderInfo.setStatus(40);
            updateOrderStatus(currentOrderInfo);
        }
    }

    @Override
    public void showComfirmOrderPaySuccess() {
        if (currentOrderInfo != null) {
            currentOrderInfo.setStatus(20);
            updateOrderStatus(currentOrderInfo);
        }
    }

    @Override
    public void showHasMessage(boolean isHasMessage) {
        switchRedPointIcon(isHasMessage);
    }

    /**
     * 更新订单状态
     *
     * @param orderInfo
     */
    private void updateOrderStatus(OtcOrderInfoResponse orderInfo) {
        //10待支付，20已支付待确认，30申诉中，40撤销，50完全成交
        int status = orderInfo.getStatus();
        if (status == 10) {
            orderStatusWaitPay(orderInfo);
        } else if (status == 20) {
            orderStatusWaitGiveB(orderInfo);
        } else if (status == 30) {
            orderStatusAppeal(orderInfo);
        } else if (status == 40) {
            orderStatusCancel(orderInfo);
        } else if (status == 50) {
            orderStatusFinished(orderInfo);
        }

    }

    /**
     * 50完全成交
     *
     * @param orderInfo
     */
    private void orderStatusFinished(OtcOrderInfoResponse orderInfo) {
        //除待支付是不可以选择的
        viewFinder.textView(R.id.order_pay_way).setEnabled(false);
        orderPayWay.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        viewFinder.find(R.id.order_status_handing_linear).setVisibility(View.GONE);
        viewFinder.find(R.id.order_status_finished_rela).setVisibility(View.VISIBLE);
        viewFinder.textView(R.id.tip_red).setVisibility(View.GONE);
        cancelBtn.setVisibility(View.GONE);
        appealBtn.setVisibility(View.GONE);
        viewFinder.textView(R.id.status_description).setText(getString(R.string.string_otc_trade_finished));
        viewFinder.textView(R.id.order_status_finished).setText(getString(R.string.string_order_status_buy_finished));
        viewFinder.textView(R.id.order_status_finished).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.icon_otc_finished), null, null, null);

    }

    /**
     * 40撤销
     *
     * @param orderInfo
     */
    private void orderStatusCancel(OtcOrderInfoResponse orderInfo) {
        //除待支付是不可以选择的
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        viewFinder.textView(R.id.order_pay_way).setEnabled(false);
        orderPayWay.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        viewFinder.find(R.id.order_status_handing_linear).setVisibility(View.GONE);
        viewFinder.find(R.id.order_status_finished_rela).setVisibility(View.VISIBLE);
        viewFinder.textView(R.id.tip_red).setVisibility(View.GONE);
        cancelBtn.setVisibility(View.GONE);
        appealBtn.setVisibility(View.GONE);
        viewFinder.textView(R.id.status_description).setText(getString(R.string.string_otc_trade_canceled));
        viewFinder.textView(R.id.order_status_finished).setText(getString(R.string.string_order_canceled));
        viewFinder.textView(R.id.order_status_finished).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.icon_cancelled), null, null, null);

    }

    /**
     * 30申诉中
     *
     * @param orderInfo
     */
    private void orderStatusAppeal(OtcOrderInfoResponse orderInfo) {
        viewFinder.find(R.id.order_status_handing_linear).setVisibility(View.VISIBLE);
        viewFinder.find(R.id.order_status_finished_rela).setVisibility(View.GONE);
        viewFinder.textView(R.id.tips_time).setText(getString(R.string.string_customer_handle, getString(R.string.app_name)));
        cancelBtn.setVisibility(View.GONE);
        appealBtn.setVisibility(View.GONE);
        //除待支付是不可以选择的
        viewFinder.textView(R.id.order_pay_way).setEnabled(false);
        orderPayWay.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        orderStatusBtn.setEnabled(false);
        orderStatusBtn.setTextColor(SkinColorUtil.getWhite(this));
        orderStatusBtn.setText(getString(R.string.string_appealing));
        if (isBuy) {
            viewFinder.textView(R.id.tip_red).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.tip_red).setText(getString(R.string.string_format_otc_buy_pay_sure_tips, orderInfo.getBuyerRealName()));
        } else {
            viewFinder.textView(R.id.tip_red).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.tip_red).setText(getString(R.string.string_format_otc_sell_give_b_sure_tips, orderInfo.getBuyerRealName()));
        }
    }

    /**
     * 20已支付待确认
     *
     * @param orderInfo
     */
    private void orderStatusWaitGiveB(OtcOrderInfoResponse orderInfo) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        viewFinder.find(R.id.order_status_handing_linear).setVisibility(View.VISIBLE);
        viewFinder.find(R.id.order_status_finished_rela).setVisibility(View.GONE);
        viewFinder.textView(R.id.tips_time).setText(getString(R.string.string_wait_seller_give_b));
        cancelBtn.setVisibility(View.GONE);
        appealBtn.setVisibility(View.VISIBLE);
        startAppealCountDownTimer(orderInfo.getAppealLastSeconds());
        //除待支付是不可以选择的
        viewFinder.textView(R.id.order_pay_way).setEnabled(false);
        orderPayWay.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        orderStatusBtn.setEnabled(false);
        orderStatusBtn.setTextColor(SkinColorUtil.getWhite(this));
        orderStatusBtn.setText(getString(R.string.string_wait_give_b));
        if (isBuy) {
            viewFinder.textView(R.id.tip_red).setVisibility(View.GONE);
            viewFinder.textView(R.id.tip_red).setText(getString(R.string.string_format_otc_buy_pay_sure_tips, orderInfo.getBuyerRealName()));
        } else {
            viewFinder.textView(R.id.tip_red).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.tip_red).setText(getString(R.string.string_format_otc_sell_give_b_sure_tips, orderInfo.getBuyerRealName()));
        }
    }

    /**
     * 10待支付
     *
     * @param orderInfo
     */
    private void orderStatusWaitPay(OtcOrderInfoResponse orderInfo) {
        viewFinder.find(R.id.order_status_handing_linear).setVisibility(View.VISIBLE);
        viewFinder.find(R.id.order_status_finished_rela).setVisibility(View.GONE);
        startCountDownTimer(orderInfo.getTransferLastSeconds());
        cancelBtn.setVisibility(View.VISIBLE);
        appealBtn.setVisibility(View.GONE);
        orderStatusBtn.setEnabled(true);
        //待支付是可以选择的
        viewFinder.textView(R.id.order_pay_way).setEnabled(true);
        orderPayWay.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.icon_arrow_right), null);
        orderStatusBtn.setTextColor(SkinColorUtil.getDark(this));
        orderStatusBtn.setText(getString(R.string.string_otc_finish_order));

        if (isBuy) {
            viewFinder.textView(R.id.tip_red).setVisibility(View.VISIBLE);
            viewFinder.textView(R.id.tip_red).setText(getString(R.string.string_format_otc_buy_pay_sure_tips, orderInfo.getBuyerRealName()));
        } else {
            viewFinder.textView(R.id.tip_red).setVisibility(View.GONE);
            viewFinder.textView(R.id.tip_red).setText(getString(R.string.string_format_otc_sell_give_b_sure_tips, orderInfo.getBuyerRealName()));
        }
    }

    /**
     * 五分钟后可申诉倒计时
     *
     * @param appealLastSeconds
     */
    private void startAppealCountDownTimer(String appealLastSeconds) {
        if (TextUtils.isEmpty(appealLastSeconds)) {
            return;
        }
        Long remainingTime = Long.valueOf(appealLastSeconds) * 1000;
        if (remainingTime > 0) {
            appealBtn.setEnabled(false);
            if (appealCountDownTimer != null) {
                return;
            }
            appealCountDownTimer = new CountDownTimer(remainingTime, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    isAppealCountDown = true;
                    appealBtn.setEnabled(millisUntilFinished <= 0);
                    TextColorUtils.setTextViewColor(appealBtn, getString(R.string.string_otc_fortmat_appeal_counter), DateUtils.getRemainingTime(OtcBuyActivity.this, millisUntilFinished), R.color.orange);
                }

                @Override
                public void onFinish() {
                    isAppealCountDown = false;
                    appealBtn.setEnabled(true);
                    appealBtn.setText(getString(R.string.string_appeal));
                }

            }.start();

        } else {
            isAppealCountDown = false;
            appealBtn.setEnabled(true);
            appealBtn.setText(getString(R.string.string_appeal));
        }
    }

    /**
     * 确认付款倒计时
     *
     * @param transferLastSeconds
     */
    private void startCountDownTimer(String transferLastSeconds) {
        if (TextUtils.isEmpty(transferLastSeconds)) {
            return;
        }
        Long remainingTime = Long.valueOf(transferLastSeconds) * 1000;
        if (remainingTime > 0) {
            cancelBtn.setEnabled(true);
            if (countDownTimer != null) {
                return;
            }
            countDownTimer = new CountDownTimer(remainingTime, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    TextColorUtils.setTextViewColor(viewFinder.textView(R.id.tips_time), getString(R.string.string_otc_fortmat_finish_order_counter), DateUtils.getRemainingTime(OtcBuyActivity.this, millisUntilFinished), R.color.orange);
                }

                @Override
                public void onFinish() {
                    viewFinder.textView(R.id.tips_time).setText(getString(R.string.string_otc_trade_canceled));
                }

            }.start();
        } else {
            cancelBtn.setEnabled(false);
        }
    }

    private void updateShowPayWay(OtcOrderInfoResponse.PaymentTermListBean paymentTermBean) {
        currentPaymentBean = paymentTermBean;
        viewFinder.textView(R.id.order_pay_way).setText(paymentTermBean.getPayName());
        if (paymentTermBean.getPaymentType() == 0) {
            //银行卡支付
            viewFinder.find(R.id.bank_cl).setVisibility(View.VISIBLE);
            viewFinder.find(R.id.wechat_alipay_cl).setVisibility(View.GONE);

            viewFinder.textView(R.id.bank_no).setText(paymentTermBean.getAccountNo());
            String bankId = paymentTermBean.getBankName();
            OtcConfigResponse.BankBean bankBean = bankMap.get(bankId);
            if (bankBean != null) {
                viewFinder.textView(R.id.bank_name).setText(bankBean.getName());
            } else {
                viewFinder.textView(R.id.bank_name).setText(paymentTermBean.getBankName());
            }
            viewFinder.textView(R.id.trade_username).setText(paymentTermBean.getRealName());
            String branchName = paymentTermBean.getBranchName();
            if (!TextUtils.isEmpty(branchName)) {
                viewFinder.textView(R.id.title_bank_branch_name).setVisibility(View.VISIBLE);
                viewFinder.textView(R.id.bank_branch_name).setVisibility(View.VISIBLE);
                viewFinder.textView(R.id.bank_branch_name).setText(branchName);
            } else {
                viewFinder.textView(R.id.title_bank_branch_name).setVisibility(View.GONE);
                viewFinder.textView(R.id.bank_branch_name).setVisibility(View.GONE);
            }


        } else if (paymentTermBean.getPaymentType() == 1 || paymentTermBean.getPaymentType() == 2) {
            //微信支付宝支付方式
            viewFinder.find(R.id.wechat_alipay_cl).setVisibility(View.VISIBLE);
            viewFinder.find(R.id.bank_cl).setVisibility(View.GONE);

            viewFinder.textView(R.id.pay_account).setText(paymentTermBean.getAccountNo());
            viewFinder.textView(R.id.pay_username).setText(paymentTermBean.getRealName());
            ImageView imageView = viewFinder.imageView(R.id.qrcode);
            String qrcodeUrl = paymentTermBean.getQrcode();
            if (!TextUtils.isEmpty(qrcodeUrl)) {
                if (qrcodeUrl.startsWith("/")) {
                    qrcodeUrl = qrcodeUrl.replaceFirst("/", "");
                }
                qrcodeUrl = UrlsConfig.API_OTC_URL + qrcodeUrl;
                imageView.setTag(qrcodeUrl);

//                CImageLoader.getInstance().load(imageView,qrcodeUrl,R.mipmap.icon_qcode);
                CImageLoader.getInstance().load(imageView, qrcodeUrl);
            }
        }

    }

    /**
     * 预览图片
     */
    private void showPicBrowser(int index, List<String> imgUrls) {

        if (imgUrls == null || index >= imgUrls.size())
            return;

        ArrayList<ImageInfo> imageInfoList = new ArrayList<>();
        ImageInfo imageInfo;
        for (String imgUrl : imgUrls) {
            imageInfo = new ImageInfo();
            // 原图地址（必填）
            imageInfo.setOriginUrl(imgUrl);
            // 缩略图地址（必填）
            // 如果没有缩略图url，可以将两项设置为一样。（注意：此处作为演示用，加了-1200，你们不要这么做）
//            imageInfo.setThumbnailUrl(image.concat("-1200"));
            imageInfo.setThumbnailUrl(imgUrl);
            imageInfoList.add(imageInfo);
            imageInfo = null;
        }

        ImagePreview.getInstance()
                .setContext(this)
                .setIndex(index)
                .setImageInfoList(imageInfoList)
                .setShowDownButton(true)
                //.setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                .setFolderName("BhexImage")
                .setScaleLevel(1, 3, 5)
                .setZoomTransitionDuration(300)

                .setEnableClickClose(true)// 是否启用点击图片关闭。默认启用
                .setEnableDragClose(true)// 是否启用上拉/下拉关闭。默认不启用

                .setShowCloseButton(true)// 是否显示关闭页面按钮，在页面左下角。默认不显示
                .setCloseIconResId(R.drawable.ic_action_close)// 设置关闭按钮图片资源，可不填，默认为：R.drawable.ic_action_close

                .setShowDownButton(true)// 是否显示下载按钮，在页面右下角。默认显示
                .setDownIconResId(R.drawable.icon_download_new)// 设置下载按钮图片资源，可不填，默认为：R.drawable.icon_download_new

                .setShowIndicator(true)// 设置是否显示顶部的指示器（1/9）。默认显示
                .start();
    }

    /**
     * 显示价格模式选择
     */
    private void showPayWaySelect() {
//        KeyBoardUtil.closeKeybord(editAmount, getContext());
        if (payWayArray == null) {
            return;
        }

        payWayAlertView = new AlertView(null, null, getString(R.string.string_cancel), null, payWayArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                String payName = payWayArray[position];
                OtcOrderInfoResponse.PaymentTermListBean paymentTermListBean = payWayMap.get(payName);
                if (paymentTermListBean != null) {
                    updateShowPayWay(paymentTermListBean);
                }
            }
        });

        payWayAlertView.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_pay_way:
                //选择支付方式
                showPayWaySelect();
                break;
            case R.id.title:
                if (currentOrderInfo != null) {
                    String amount = currentOrderInfo.getAmount();
                    if (!TextUtils.isEmpty(amount)) {
                        CommonUtil.copyText(this, amount);
                    }
                }
                break;
            case R.id.qrcode:
                //二维码
//                AnimalUtils.scaleXYAnimRun(viewFinder.imageView(R.id.qrcode),1.0f,10.0f);
                String qrcodeUrl = (String) v.getTag();
                List<String> urls = new ArrayList<>();
                urls.add(qrcodeUrl);
                showPicBrowser(0, urls);
                break;
            case R.id.order_id:
                CommonUtil.copyText(this, viewFinder.textView(R.id.order_id).getText().toString());
                break;
            case R.id.bank_no_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.bank_no).getText().toString());
                break;
            case R.id.bank_name_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.bank_name).getText().toString());
                break;
            case R.id.bank_branch_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.bank_branch_name).getText().toString());
                break;
            case R.id.trade_username_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.trade_username).getText().toString());
                break;
            case R.id.pay_account_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.pay_account).getText().toString());
                break;
            case R.id.pay_username_copy:
                CommonUtil.copyText(this, viewFinder.textView(R.id.pay_username).getText().toString());
                break;
            case R.id.btn_cancel:
                DialogUtils.showDialog(this, "", getString(R.string.string_otc_cancel_order_tips), getString(R.string.string_confirm_cancel), getString(R.string.string_give_up), true, new DialogUtils.OnButtonEventListener() {
                    @Override
                    public void onConfirm() {
                        getPresenter().orderCancel();
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                break;
            case R.id.btn_appeal:
                getPresenter().goOrderAppeal();

                break;
            case R.id.order_status_btn:
                if (currentPaymentBean != null) {
                    boolean isFirstOtcBuy = SPEx.get("isFirstOtcBuy", true);
                    if (isFirstOtcBuy) {
                        showFirstTipsDialog();
                    } else {
                        //支付确认框
                        showPayConfirmDialog();
                    }

                } else {
                    ToastUtils.showLong(getString(R.string.string_please_select_otc_pay_way));
                }

                break;
        }
    }

    /**
     * 首次交易-弹窗提示支付方式
     */
    private void showFirstTipsDialog() {
        DialogUtils.showDialogOneBtn(this, "", getString(R.string.string_comfirm_pay_tips), getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {

            @Override
            public void onConfirm() {
                SPEx.set("isFirstOtcBuy", false);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * 支付确认框
     */
    private void showPayConfirmDialog() {
        if (currentOrderInfo != null) {
            String title = getString(R.string.string_format_pay_confirm_title, currentOrderInfo.getAmount(), currentOrderInfo.getCurrencyId());
            String content = getString(R.string.string_otc_conirm_pay_import_tips);
            String btnConfirm = getString(R.string.string_otc_confirm_pay);
            String btnCancel = "";
            DialogUtils.showOtcPayConfirm(this, bankMap, currentOrderInfo, currentPaymentBean, title, content, btnConfirm, btnCancel, false, new DialogUtils.OnOtcEventListener() {
                @Override
                public void onConfirm(String tradePasswd) {
                    getPresenter().orderPay(currentPaymentBean);
                }

                @Override
                public void onCancel() {

                }
            });

        }
    }

    private HashMap<String, OtcConfigResponse.BankBean> bankMap = new HashMap<>();

    @Override
    public void showBankList(List<OtcConfigResponse.BankBean> bankList) {
        if (bankList != null) {
            bankMap.clear();
            for (OtcConfigResponse.BankBean bankBean : bankList) {
                bankMap.put(bankBean.getBankId(), bankBean);
            }
        }
    }
}
